"""
@Project:p7_2109
@File:jwt_util.py
@Author:马可
@Date:下午 03:15
"""

import jwt
from datetime import datetime, timedelta
from flask import current_app


def generate_token(payload,expiry,algorithm='HS256'):
    """生成token"""
    key = current_app.config.get('SECRET_KEY')
    if 'exp' not in payload:
        payload['exp'] = expiry
    try:
        token = jwt.encode(payload, key, algorithm)
        return token
    except Exception as e:
        print('generate_token error', e)
        return e



def check_token(token):
    """校验token"""
    key = current_app.config.get('SECRET_KEY')
    payload = jwt.decode(token, key, algorithms=["HS256"])
    return payload


def _generate_token(payload, is_refresh=True):
    # 设置有效期, 第一默认生成2个小时的有效期
    expiry = datetime.now() + timedelta(seconds=30)
    token = 'JWT' + generate_token(payload, expiry)
    # 默认需要刷新生成token
    if is_refresh:
        # 刷新生成的token,有效期15天
        expiry = datetime.now() + timedelta(days=15)
        # 给payload 添加刷新token的标识
        payload.update({is_refresh:True})
        print("jwt util payload--->",payload)
        refresh_token = "JWT" + generate_token(payload,expiry)
    else:
        refresh_token = None
    return token, refresh_token
